package com.wyw.core.config.support;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.sf.ehcache.Cache;

import org.jdom.Document;
import org.jdom.Element;

import com.wyw.core.config.XmlConfigParse;
import com.wyw.core.exception.WYWException;
import com.wyw.core.secu.dto.GroupRoleMapping;
import com.wyw.core.secu.dto.XmlConfigType;
import com.wyw.core.util.CacheManager;

public class SecurityGroupRoleParse implements XmlConfigParse{

	@Override
	public void parse(XmlConfigType xmlConfigType, Document xmlConfig)throws Exception {
		// TODO Auto-generated method stub
		List<Element> groupListConfig=xmlConfig.getRootElement().getChildren();
		List groupList = new ArrayList();
		HashMap groupMap = new HashMap();
		GroupRoleMapping groupRoleMapping;
		for(Element element : groupListConfig){
			groupRoleMapping= new GroupRoleMapping();
			parseGroup(element, groupRoleMapping ,groupMap);
			groupList.add(groupRoleMapping);
		}
		net.sf.ehcache.Element configList=new  net.sf.ehcache.Element(CacheManager.security_group_role_list,groupList);
		CacheManager.put(configList);
		
		net.sf.ehcache.Element configMap=new  net.sf.ehcache.Element(CacheManager.security_group_role_map,groupMap);
		CacheManager.put(configMap);
	}
	
	private void parseGroup(Element groupElement,GroupRoleMapping groupRoleMapping,HashMap groupMap)throws Exception{
		String id=groupElement.getAttributeValue("id");
		groupRoleMapping.setId(id);
		
		String name=groupElement.getAttributeValue("name");
		groupRoleMapping.setName(name);
		
		if(groupMap.containsKey(id)){
			throw new WYWException("组：id="+id+" name="+name+"已存在！");
		}
		groupMap.put(id, groupRoleMapping);
		
		String desc=groupElement.getChildText("desc");
		groupRoleMapping.setName(name);
		Element roleListElement=groupElement.getChild("roleList");
		if(roleListElement ==null || roleListElement.getChildren() ==null){
			throw new WYWException("组：id="+id+" name="+name+"角色列表为空！");
		}
		
		//System.out.println("组：id="+id+" name="+name);
		List groupRoleList = new ArrayList();
		List<Element> roleList=roleListElement.getChildren();
		for(Element role:roleList){
			groupRoleList.add(role.getText());
		}
		groupRoleMapping.setRoleList(groupRoleList) ;
		 
		if(groupElement.getChild("childGroupList") !=null){
			List<Element> childGroupList=groupElement.getChild("childGroupList").getChildren();
			GroupRoleMapping groupRoleMappingCh;
			List childGroup= new ArrayList();
			for(Element childGroupEl:childGroupList){
				groupRoleMappingCh = new GroupRoleMapping();
				groupRoleMappingCh.setParentGroup(groupRoleMapping);
				parseGroup(childGroupEl,groupRoleMappingCh ,groupMap);
				childGroup.add(groupRoleMappingCh);
			}
			groupRoleMapping.setChildGroupList(childGroup);
		}
	}
}
